from django.core.validators import FileExtensionValidator,get_available_image_extensions
from rest_framework import serializers

class UploadImageSerializer(serializers.Serializer):
    allowed_extensions = get_available_image_extensions()
    image = serializers.ImageField(
        validators=[FileExtensionValidator(allowed_extensions)],
        error_messages = {'required':'请上传图片','invalid_image':'请上传正确格式的图片'}
    )

    def validate_image(self,value):
        max_size = 0.5 * 1024 * 1024
        size = value.size
        if size > max_size:
            raise serializers.ValidationError('图片最大不能超过0.5M')
        return value
